from django import http
from django.core.cache import cache
from django.db import DatabaseError
from django.shortcuts import render

# Create your views here.
from django.views import View

from homes.models import Area
from utils.response_code import RET


class AreasView(View):
    def get(self, requerst):

        areas_list = cache.get('area_info')

        if not areas_list:
            try:
                areas = Area.objects.all()
            except DatabaseError as e:
                return http.JsonResponse({"errno": RET.DBERR, "errmsg": "数据库查询失败"})

            areas_list = [area.to_dict() for area in areas]

            cache.set('area_info', areas_list, 3600)

        return http.JsonResponse({"errno": RET.OK, "errmsg": "获取成功", "data": areas_list})
